package com.sto.stoapp.thread;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.util.Log;

import com.google.gson.Gson;
import com.sto.stoapp.entity.BillPaymentEntity;
import com.sto.stoapp.entity.HelpGetPaymentEntity;
import com.sto.stoapp.entity.HelpGetPaymentResultEntity;
import com.sto.stoapp.http.HttpManager;
import com.sto.stoapp.util.NetUtil;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by wj on 2016-12-30.
 *
 * 代收货款的线程
 */

public class HelpGetPaymentThread extends Thread{

    public static final int MSG_WHAT=1;

    private String bill;
    private Context context;
    private Handler handler;

    public static final String ECCOMPANYID="STOPDA";
    public static final String KEY="093343CD3519840A";

    private String test_url="http://222.66.109.134:22226/stoPlatform/cod/codOperate!codQuery.action";
    private String nomal="http://222.66.39.203:22221/stoPlatform/cod/codOperate!codQuery.action";

    public HelpGetPaymentThread(String bill, Context context , Handler handler){
        this.bill=bill;
        this.context=context;
        this.handler=handler;
    }

    @Override
    public void run() {
        super.run();

        //判断是否有网络连接
        if(!NetUtil.isNetworkAvailable(context))
            return;

        if(null==bill || "".equals(bill))
            return;

        HelpGetPaymentEntity entity=new HelpGetPaymentEntity();
        entity.setEccompanyid(ECCOMPANYID);
        List<HelpGetPaymentEntity.CodsBean> list=new ArrayList<HelpGetPaymentEntity.CodsBean>();
        HelpGetPaymentEntity.CodsBean bean=new HelpGetPaymentEntity.CodsBean();
        bean.setBillCode(bill);
        bean.setQueryTime(getCurrentTiem());
        list.add(bean);
        entity.setCods(list);
        Gson gson=new Gson();
        String logistics_interface=gson.toJson(entity);

        String md5str=getMD5Str(logistics_interface+KEY);
        String data_digest=new String(Base64.encode(md5str.getBytes(),Base64.NO_WRAP));

        Log.e("wj",data_digest);

        ArrayList<NameValuePair> pairs=new ArrayList<NameValuePair>();
        NameValuePair pair1=new BasicNameValuePair("eccompanyid",ECCOMPANYID);
        NameValuePair pair2=new BasicNameValuePair("msg_type","CODQUERY");
        NameValuePair pair4=new BasicNameValuePair("data_digest",data_digest);
        NameValuePair pair3=new BasicNameValuePair("logistics_interface",logistics_interface);

        pairs.add(pair1);
        pairs.add(pair2);
        pairs.add(pair4);
        pairs.add(pair3);

        String result=HttpManager.doPost(nomal,pairs);
        if(null!=result){
            Log.e("wj",result);
            HelpGetPaymentResultEntity resultBean=gson.fromJson(result, HelpGetPaymentResultEntity.class);
            if("true".equals(resultBean.getSuccess())){
                if("true".equals(resultBean.getResponseItems().get(0).getSuccess())){
                    Message msg=new Message();
                    msg.what=MSG_WHAT;
                    BillPaymentEntity billPaymentEntity=new BillPaymentEntity();
                    billPaymentEntity.setBillNo(bill);
                    billPaymentEntity.setBillPayment(resultBean.getResponseItems().get(0).getCodAmount());
                    msg.obj=billPaymentEntity;
                    handler.sendMessage(msg);
                }
            }
        }

    }

    private String getCurrentTiem(){
        Date date=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         return sdf.format(date);
    }

    /**
     * md5加密
     * @param str
     * @return
     */
    private static String getMD5Str(String str) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(str.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        byte[] byteArray = messageDigest.digest();
        StringBuffer md5StrBuff = new StringBuffer();
        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
                md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
            else
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
        }
        return md5StrBuff.toString();
    }

}
